package org.ielts.action;

import static com.yifeng.struts2.ActionUtils.put;
import static com.yifeng.struts2.ResultConstants.FILL;
import static com.yifeng.struts2.ResultConstants.JSON;
import static com.yifeng.struts2.ResultParameters.setJson;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.ielts.domain.Mark;
import org.ielts.domain.base.Lesson;
import org.ielts.domain.base.SignCourse;
import org.ielts.domain.base.Student;
import org.ielts.domain.log.OrderLessonLog;
import org.ielts.domain.report.LessonWithListenerCount;
import org.ielts.service.FrontService;
import org.ielts.service.LessonService;
import org.ielts.service.OrderLessonLogService;
import org.ielts.service.OrderLessonService;
import org.ielts.service.SignCourseService;
import org.ielts.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;

import com.yifeng.ProfileContext;
import com.yifeng.TimePair;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.utils.JsonResultBuilder;

public class OrderLessonAction extends BaseAction {

	@Autowired
	LessonService lessonService;

	@Autowired
	OrderLessonService orderLessonService;

	@Operation(result = FILL)
	public String orderLesson() {
		String signCourseId = form.readString("signCourseId");

		Date today = DateUtils.truncate(new Date(), Calendar.DATE);

		Date beginTime = valueReader.name("startDate").defaultValue(today).dateValue("yyyy-MM-dd");
		Date endTime = DateUtils.addDays(beginTime, 1);

		Iterable<LessonWithListenerCount> reports = lessonService.findReportBetweenDate(beginTime, endTime);

		Date preTime = DateUtils.addDays(beginTime, -1);

		put("preDate", new SimpleDateFormat("yyyy-MM-dd").format(preTime));
		put("currentDate", new SimpleDateFormat("yyyy-MM-dd").format(beginTime));
		put("nextDate", new SimpleDateFormat("yyyy-MM-dd").format(endTime));
		put("reports", reports);

		put("signCourseId", signCourseId);

		return FILL;
	}

	@Operation(result = JSON)
	public String doOrderLesson() {
		String lessonId = form.readString("lessonId");
		String signCourseId = form.readString("signCourseId");
		Collection<OrderLessonLog> ols = frontService.findOrderLessonLog(signCourseId, new String[] { lessonId });
		if (ols.size() == 0) {
			OrderLessonLog orderLessonLog = frontService.orderLesson(signCourseId, lessonId);
			setJson(JsonResultBuilder.success(true).msg("订课成功").add("id", orderLessonLog.getStudent().getId()).json());
		} else {
			setJson(JsonResultBuilder.success(false).msg("您已经订过该课程！无法重复订课！").json());
		}

		return JSON;
	}

	public TimePair getRequestTimePair() {
		Date startDate = valueReader.name("startDate").defaultValue(null).dateValue("yyyy-MM-dd");
		Date endDate = valueReader.name("endDate").defaultValue(null).dateValue("yyyy-MM-dd");
		if (endDate != null) {
			endDate = DateUtils.addDays(endDate, 1);
		}

		if (startDate == null || endDate == null) {
			Calendar calendar = Calendar.getInstance();
			calendar.setFirstDayOfWeek(Calendar.MONDAY);
			calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

			startDate = calendar.getTime();
			endDate = DateUtils.addDays(startDate, 7);
		}

		TimePair timePair = new TimePair();
		timePair.setStartDate(startDate);
		timePair.setEndDate(endDate);

		return timePair;
	}

	@Operation(result = JSON)
	public String doViewScheduleByDay() {

		Date today = new Date();
		today = DateUtils.truncate(today, Calendar.DATE);
		Date startDate = valueReader.name("day").defaultValue(today).dateValue("yyyy-MM-dd");
		Date endDate = DateUtils.addDays(startDate, 1);

		Iterable<LessonWithListenerCount> lessons = lessonService.findReportBetweenDate(startDate, endDate);

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(new String[] { "courses", "roles", "hibernateLazyInitializer", "orderLessonLogs",
				"orders", "teachings" });
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

		JSONArray jsonArray = JSONArray.fromObject(lessons, jsonConfig);

		setJson(JsonResultBuilder.success(true).msg("列出课程成功").add("lessons", jsonArray).json());

		return JSON;
	}

	@Autowired
	FrontService frontService;

	@Operation(result = JSON)
	public String doCancelOrderLesson() {
		String id = form.readString("id");

		OrderLessonLog orderLessonLog = frontService.cancelOrderLesson(id);

		Lesson lesson = orderLessonLog.getLesson();

		setJson(JsonResultBuilder.success(true).msg("取消订课成功").add("lessonId", lesson != null ? lesson.getId() : null)
				.json());

		return JSON;
	}

	@Operation(result = JSON)
	public String refreshLesson() {
		String lessonId = form.readString("lessonId");

		Lesson lesson = lessonService.findOne(lessonId);
		long count = orderLessonService.countByLesson(lessonId);

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setExcludes(new String[] { "roles", "courses", "consultStatus", "teachings", "orderLessonLogs",
				"signCourseLogs", "schoolLogs", "orders" });
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

		JSONObject jsonObject = JSONObject.fromObject(lesson, jsonConfig);

		setJson(JsonResultBuilder.success(true).msg("取消订课成功").add("lesson", jsonObject).add("count", count).json());

		return JSON;
	}

	@Autowired
	OrderLessonLogService orderLessonLogService;

	@Operation(result = JSON)
	public String doMarkGoodOrderLesson() {

		String id = form.readString("id");

		orderLessonLogService.markLesson(id, Mark.Good);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());

		return JSON;
	}

	@Operation(result = JSON)
	public String doMarkBadOrderLesson() {

		String id = form.readString("id");

		orderLessonLogService.markLesson(id, Mark.Bad);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());

		return JSON;
	}

	@Operation(result = JSON)
	public String doResetOrderLesson() {

		String id = form.readString("id");

		orderLessonLogService.resetOrderLesson(id);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());

		return JSON;
	}

	@Operation(result = JSON)
	public String doRemarkLog() {

		String id = form.readString("id");
		String remark = form.readString("remark");

		orderLessonLogService.remarkOrderLesson(id, remark);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());

		return JSON;
	}

	@Operation(result = JSON)
	public String doEarlyOrderLesson() {
		String id = form.readString("id");

		orderLessonLogService.earlyOrderLesson(id);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());
		return JSON;
	}

	@Operation(result = JSON)
	public String doLateOrderLesson() {
		String id = form.readString("id");

		orderLessonLogService.lateOrderLesson(id);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());
		return JSON;
	}

	@Operation(result = JSON)
	public String doUnValidOrderLesson() {
		String id = form.readString("id");

		orderLessonLogService.validOrderLesson(id, false);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());
		return JSON;
	}

	@Operation(result = JSON)
	public String doValidOrderLesson() {
		String id = form.readString("id");

		orderLessonLogService.validOrderLesson(id, true);

		setJson(JsonResultBuilder.success(true).msg("操作成功").json());
		return JSON;
	}

	@Autowired
	SignCourseService signCourseService;

	@Operation(result = FILL)
	public String orderHistoryLesson() {
		String signCourseId = form.readString("signCourseId");

		SignCourse signCourse = signCourseService.findOne(signCourseId);

		put("signCourse", signCourse);

		return FILL;
	}

	@Operation(result = JSON)
	public String doOrderHistoryLesson() throws ParseException {
		String signCourseId = form.readString("signCourseId");

		String day = form.readString("date");
		String beginTimeStr = form.readString("beginTime");
		String endTimeStr = form.readString("endTime");

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		Date beginTime = simpleDateFormat.parse(day + " " + beginTimeStr);
		Date endTime = simpleDateFormat.parse(day + " " + endTimeStr);

		String title = form.readString("title");

		OrderLessonLog orderLessonLog = orderLessonService.orderHistoryLesson(signCourseId, title, beginTime, endTime);

		setJson(JsonResultBuilder.success(true).msg("记录历史课程成功").add("id", orderLessonLog.getStudent().getId()).json());

		return JSON;
	}

	@Autowired
	StudentService studentService;

	@Operation(result = FILL)
	public String orderAuditionLesson() {
		String studentId = form.readString("studentId");

		Student student = studentService.findOne(studentId);

		Date today = DateUtils.truncate(new Date(), Calendar.DATE);

		Date beginTime = valueReader.name("startDate").defaultValue(today).dateValue("yyyy-MM-dd");
		Date endTime = DateUtils.addDays(beginTime, 1);

		Iterable<LessonWithListenerCount> reports = lessonService.findReportBetweenDate(beginTime, endTime);

		Date preTime = DateUtils.addDays(beginTime, -1);

		put("preDate", new SimpleDateFormat("yyyy-MM-dd").format(preTime));
		put("currentDate", new SimpleDateFormat("yyyy-MM-dd").format(beginTime));
		put("nextDate", new SimpleDateFormat("yyyy-MM-dd").format(endTime));
		put("reports", reports);

		put("student", student);

		return FILL;
	}

	@Operation(result = FILL)
	public String doOrderAuditionLesson() {
		String lessonId = form.readString("lessonId");
		String studentId = form.readString("studentId");

		List<OrderLessonLog> ols = frontService.findOrderLessonLogByLessonAndStudent(lessonId, studentId);
		if (ols.size() == 0) {
			OrderLessonLog orderLessonLog = frontService.orderAuditionLesson(studentId, lessonId);

			setJson(JsonResultBuilder.success(true).msg("订课成功").add("id", orderLessonLog.getStudent().getId()).json());
		} else {
			setJson(JsonResultBuilder.success(false).msg("已经试听该课程！无法重复试听！").json());
		}
		return JSON;
	}
}
